﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Net;
using System.IO;

using System.Linq;
using System.Xml.Linq;

namespace WindowsAzure_StorageREST
{
    public class StorageResponse
    {
        public HttpStatusCode ResponseCode { get; set; }

        public string ResponseMessage { get; set; }

        public string ResponseBody { get; set; }

        public WebHeaderCollection ResponseHeaders { get; set; }

        public StorageResponse()
        {
        }

        public StorageResponse(HttpWebResponse response)
        {
            this.ResponseCode = response.StatusCode;
            this.ResponseMessage = response.StatusDescription;
            this.ResponseBody = ReadStream(response.GetResponseStream());
            this.ResponseHeaders = response.Headers;
        }

        public ErrorResponse GetErrorResponse()
        {
            ErrorResponse error = null;
            if (ResponseBody.Length > 0)
            {
                XDocument doc = XDocument.Parse(ResponseBody);

                if (doc.Root.Name.LocalName.Equals("Error", StringComparison.CurrentCultureIgnoreCase))
                {
                    error = new ErrorResponse()
                        {
                            Code = doc.Root.Element("Code").Value,
                            Message = doc.Root.Element("Message").Value
                        };
                }
            }

            return error;
        }

        private string ReadStream(Stream body)
        {
            using (System.IO.StreamReader sr = new System.IO.StreamReader(body))
            {
                return sr.ReadToEnd();
            }
        }
    }
}
